<template>
  <el-form ref="form" label-width="80px" size="small">
    <el-form-item label="图层地址">
      <el-input v-model="layerUrl"></el-input>
    </el-form-item>
    <el-form-item label="图层类型">
      <el-select v-model="layerType" placeholder="请选择">
        <el-option
          v-for="item in typeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </el-form-item>
    <div style="padding-bottom:16px;text-align:right">
      <el-button @click="loadLayer" size="small" type="primary">载入图层</el-button>
      <el-button @click="clearLayers" size="small">清除图层</el-button>
    </div>
  </el-form>
</template>

<script>
import layer from '@/components/dogeo/cesium/layer.js'

export default {
  name: 'tool-locate',

  props: {
    viewer: {
      type: Object,
      default () {
        return null
      }
    }
  },

  data () {
    return {
      typeOptions: [
        {label: 'WMTS', value: 'wmts'},
        {label: 'WMS', value: 'wms'},
        {label: 'UT', value: 'ut'},
        {label: 'GeoJson', value: 'geojson'},
        {label: 'KML', value: 'kml'}
      ],
      layerUrl: '',
      layerType: 'wmts',
      ids: []
    }
  },

  watch: {
    layerUrl () {
      if (/wmts/i.test(this.layerUrl)) {
        this.layerType = 'wmts'
      } else if (/wms/i.test(this.layerUrl)) {
        this.layerType = 'wms'
      } else if (/\/{?x}?\/{?y}?|\/{?y}?\/{?x}?|x={x}/i.test(this.layerUrl)) {
        this.layerType = 'ut'
      } else if (/json/i.test(this.layerUrl)) {
        this.layerType = 'geojson'
      } else if (/kml/i.test(this.layerUrl)) {
        this.layerType = 'kml'
      }
    }
  },

  methods: {
    run () {
      if (!this.viewer) {
        return true
      }
      this.loadLayer()
    },
    // 加载图层
    loadLayer () {
      if (!this.layerUrl) {
        this.$message({
          type: 'error',
          message: '未输入图层地址'
        })
        return true
      }
      let id = Date.now()
      let params = {
        id: id,
        url: this.layerUrl,
        type: this.layerType,
        isShow: true
      }
      // 打开进度条
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      Promise.resolve(layer.loadLayer(params)).then((res) => {
        if (/geo|kml/i.test(this.layerType)) {
          this.viewer.zoomTo(res)
        }
      }).finally(() => {
        // 关闭进度条
        loading.close()
      })
      this.ids.push(id)
    },
    // 清除图层
    clearLayers () {
      layer.clearLayers(this.ids)
      this.ids = []
    },
    clear () {
      if (this.entity) {
        this.viewer.entities.remove(this.entity)
        this.entity = null
      }
    }
  }
}
</script>